package com.ktg.mes.dv.controller;

import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ktg.common.core.domain.APIResult;
import com.ktg.mes.dv.domain.DvWarmHumidData;
import com.ktg.mes.util.LGQueryWrapper;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ktg.common.annotation.Log;
import com.ktg.common.core.controller.BaseController;
import com.ktg.common.enums.BusinessType;
import com.ktg.common.core.domain.Result;
import com.ktg.mes.dv.domain.DvTemperatureData;
import com.ktg.mes.dv.service.IDvTemperatureDataService;
import com.ktg.common.utils.poi.ExcelUtil;

/**
 * 温度数据Controller
 *
 * @author byteco
 * @date 2022-11-30
 */
@RestController
@RequestMapping("/dv/dvTemperatureData")
public class DvTemperatureDataController extends BaseController
{
    @Autowired
    private IDvTemperatureDataService dvTemperatureDataService;

    /**
     * 查询温度数据列表
     */
    @PreAuthorize("@ss.hasPermi('dv:dvTemperatureData:list')")
    @GetMapping("/list")
    public Result<IPage<DvTemperatureData>> list(DvTemperatureData dvTemperatureData,
                                            @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                            @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                            HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询温度数据列表",req,null);
        try {
            Page<DvTemperatureData> page = new Page<DvTemperatureData>(pageNo, pageSize);
            QueryWrapper<DvTemperatureData> lqw = new LGQueryWrapper(dvTemperatureData,req.getParameterMap());
            IPage<DvTemperatureData> pageList = dvTemperatureDataService.page(page,lqw);
            return apiLog.ok(pageList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 查询电表按分钟区分的数据数据，按1200 之内条数据统计展示
     */
    @PreAuthorize("@ss.hasPermi('dv:dvTemperatureData:list')")
    @GetMapping("/chartMinute")
    public Result<IPage<DvWarmHumidData>> chartMinute(DvTemperatureData dvTemperatureData,
                                                      @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
                                                      @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
                                                      HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("查询电表数据列表",req,null);
        try {
            //获取总数量
            QueryWrapper<DvTemperatureData> lqw = new LGQueryWrapper(dvTemperatureData,req.getParameterMap());
            lqw.select("COUNT(0) as count,MIN(DISTINCT(create_time)) as startTime,MAX(create_time) as endTime");
            Map findMap = dvTemperatureDataService.getMap(lqw);
            if (findMap == null || findMap.get("count") == null || Long.valueOf(findMap.get("count").toString()) == 0){
                return apiLog.ok(null);
            };
            Long count = Long.valueOf(findMap.get("count").toString());

            //默认统计类型，如果数据太多修改统计时间
            String[] dateStr = {"DATE_FORMAT(create_time,'%Y-%m-%d %H:%i分')"
                    ,"DATE_FORMAT(create_time,'%Y-%m-%d %H时')"
                    ,"DATE_FORMAT(create_time,'%Y-%m-%d')"
                    ,"DATE_FORMAT(create_time,'%Y-%m')"
            };
            int[] spaceList = {60*60*30
                    ,60*60*24*30
                    ,60*60*24*30*30
                    ,60*60*24*30*12*30
            };

            String selectDateStr = "DATE_FORMAT(create_time,'%Y-%m-%d %H:%i:%s')";
            if (count > 60){
                for(int i = 0; i < dateStr.length; i++) {
                    if (count > spaceList[i]){
                        continue;
                    }else {
                        selectDateStr = dateStr[i];
                        break;
                    }
                };
            }

            //获取统计数据
            QueryWrapper<DvTemperatureData> tQueryWrapper = new LGQueryWrapper(dvTemperatureData,req.getParameterMap());
            tQueryWrapper.ge("temp1",1);
//            tQueryWrapper.orderByAsc("create_time");
            tQueryWrapper.isNotNull("device_name");
            tQueryWrapper.notIn("device_name","");
//            tQueryWrapper.select(selectDateStr+" as aday,MAX(temp1) as tempSd,device_name as name");
//            tQueryWrapper.groupBy(selectDateStr);

            tQueryWrapper.select(selectDateStr+" as aday,temp1,device_name");
            String selectColumn = " distinct on (aday) aday, MAX ( temp1 ) OVER (PARTITION BY aday) as \"tempSd\", device_name  AS NAME ";

            List mapList = dvTemperatureDataService.chartMinute(tQueryWrapper,selectColumn);
            return apiLog.ok(mapList);
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 导出温度数据列表
     */
    @PreAuthorize("@ss.hasPermi('dv:dvTemperatureData:export')")
    @Log(title = "温度数据", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DvTemperatureData dvTemperatureData,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("导出温度数据列表",req,dvTemperatureData);
        try {
            List<DvTemperatureData> list = dvTemperatureDataService.queryList(dvTemperatureData);
            ExcelUtil<DvTemperatureData> util = new ExcelUtil<DvTemperatureData>(DvTemperatureData.class);
            util.exportExcel(response, list, "温度数据数据");
            apiLog.ok(null);
        }catch (Exception e){
            apiLog.error(e);
        }
    }

    /**
     * 获取温度数据详细信息
     */
    @PreAuthorize("@ss.hasPermi('dv:dvTemperatureData:query')")
    @GetMapping(value = "/{recordId}")
    public Result<DvTemperatureData> getInfo(@PathVariable("recordId") Long recordId,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("获取温度数据详细信息",req,null);
        try {
            return apiLog.ok(dvTemperatureDataService.getInfo(recordId));
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 新增温度数据
     */
    @PreAuthorize("@ss.hasPermi('dv:dvTemperatureData:add')")
    @Log(title = "温度数据", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public Result<String> add(@RequestBody DvTemperatureData dvTemperatureData,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("新增温度数据",req,dvTemperatureData);
        try {
            dvTemperatureDataService.insert(dvTemperatureData);
            return apiLog.ok("添加成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 修改温度数据
     */
    @PreAuthorize("@ss.hasPermi('dv:dvTemperatureData:edit')")
    @Log(title = "温度数据", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public Result<String> edit(@RequestBody DvTemperatureData dvTemperatureData,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("修改温度数据",req,dvTemperatureData);
        try {
            dvTemperatureDataService.update(dvTemperatureData);
            return apiLog.ok("编辑成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }
    }

    /**
     * 删除温度数据
     */
    @PreAuthorize("@ss.hasPermi('dv:dvTemperatureData:remove')")
    @Log(title = "温度数据", businessType = BusinessType.DELETE)
	@DeleteMapping("/{recordIds}")
    public Result<String> remove(@PathVariable Long[] recordIds,HttpServletRequest req)
    {
        APIResult apiLog = new APIResult("删除温度数据",req,null);
        try {
            dvTemperatureDataService.delete(recordIds);
            return apiLog.ok("删除成功！");
        }catch (Exception e){
            return apiLog.error(e);
        }

    }
}
